package com.maint.m

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.view.View
import android.widget.Button
import android.widget.LinearLayout
import android.widget.TextView
import android.widget.Toast
import androidx.activity.viewModels
import androidx.core.os.postDelayed
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.maint.m.data.GlobalData

import com.maint.m.utils.XunfeiTtsUtil
import com.maint.m.utils.AppDataManager
import com.maint.m.TicketItem as OldTicketItem
import com.maint.m.data.model.TicketDetail
import com.maint.m.data.model.TicketItem
import com.maint.m.viewmodel.TicketDetailViewModel
import com.rokid.security.phone.sdk.api.PSecuritySDK
import com.rokid.security.sdk.base.common.notifacation.NotificationMessage

class TicketDetailActivity : BaseActivity() {

    private val viewModel: TicketDetailViewModel by viewModels()
    
    private lateinit var recyclerView: RecyclerView
    private lateinit var adapter: TicketDetailAdapter

    private val mainHandler = Handler(Looper.getMainLooper())

    private var tiketId: String? = null

    private var isConnected = false
    private val TAG = "TicketDetailActivity::"

    private var hasLoadedDetail = false
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        Log.i("TicketDetailActivity", "onCreate被调用")
        try {
            setContentView(R.layout.activity_ticket_detail)

            // 设置标题栏文字
            setToolbarTitle("操作票详情")

            // 启用返回按钮
            supportActionBar?.setDisplayHomeAsUpEnabled(true)

            // 初始化 RecyclerView
            initRecyclerView()
            
            // 观察ViewModel的数据变化
            observeViewModel()

            // 获取传递的数据
            val ticketItem = intent.getSerializableExtra("ticket_item") as? OldTicketItem


            if (ticketItem != null) {
                // 先显示基本信息
                bindBasicInfo(ticketItem)

                // 获取详细信息 - 添加标志确保只调用一次
                if (ticketItem.id != null && !hasLoadedDetail) {
                    Log.i("TicketDetailActivity", "首次调用loadTicketDetail，ID: ${ticketItem.id}")
                    viewModel.loadTicketDetail(ticketItem.id)
                    tiketId = ticketItem?.id
                    hasLoadedDetail = true
                }
            } else {
                showError("未获取到票务信息")
            }

            // 初始化底部悬浮按钮并添加点击事件
            initBottomButton()


            // 发送WebSocket消息
            val webSocketMessage1 = "{\"business\": 1}"
            val webSocketMessage2 = "{\"business\": 11, \"instruct\": 1}"
            sendWebSocketMessage(webSocketMessage1, showToast = false)
            mainHandler.postDelayed({
                sendWebSocketMessage(webSocketMessage2, showToast = false)
            }, 1000)
        } catch (e: Exception) {
            Log.e("TicketDetail", "OnCreate异常", e)
            showError("页面初始化失败: ${e.message}")
        }
    }
    
    private fun observeViewModel() {
        viewModel.ticketDetail.observe(this) { ticketDetail ->
            bindDetailInfo(ticketDetail)
        }
        
        viewModel.isLoading.observe(this) { isLoading ->
            // 可以在这里显示或隐藏加载指示器
        }
        
        viewModel.errorMessage.observe(this) { errorMsg ->
            errorMsg?.let {
                showError(it)
            }
        }
    }

    private fun initRecyclerView() {
        try {
            recyclerView = findViewById(R.id.rvOperationItems)
            recyclerView.layoutManager = LinearLayoutManager(this)
            adapter = TicketDetailAdapter(emptyList())
            recyclerView.adapter = adapter
        } catch (e: Exception) {
            Log.e("TicketDetail", "RecyclerView初始化失败", e)
            throw e
        }
    }

    private fun bindBasicInfo(ticketItem: OldTicketItem) {
        // 注意：这里可以直接使用，因为BaseActivity已经设置了布局
        val dispatchOrderNumberText = findViewById<TextView>(R.id.tvDetailDispatchOrderNumber)
        val unitText = findViewById<TextView>(R.id.tvDetailUnit)
        val serialNumberText = findViewById<TextView>(R.id.tvDetailSerialNumber)
        val operationTaskText = findViewById<TextView>(R.id.tvDetailOperationTask)

        dispatchOrderNumberText.text = ticketItem.dispatchOrderNumber ?: "未知"
        unitText.text = ticketItem.unit ?: "未知"
        serialNumberText.text = ticketItem.id ?: "未知"
        operationTaskText.text = ticketItem.operationTask ?: "未知"
    }


    private fun bindDetailInfo(detail: TicketDetail) {
        try {
            // 显示基本信息
            val dispatchOrderNumberText = findViewById<TextView>(R.id.tvDetailDispatchOrderNumber)
            val unitText = findViewById<TextView>(R.id.tvDetailUnit)
            val serialNumberText = findViewById<TextView>(R.id.tvDetailSerialNumber)
            val operationTaskText = findViewById<TextView>(R.id.tvDetailOperationTask)

            dispatchOrderNumberText.text = detail.dispatchOrderNumber
            unitText.text = detail.unit
            serialNumberText.text = detail.serialNumber
            operationTaskText.text = detail.operationTask

            // 更新操作项目列表
            if (::recyclerView.isInitialized && ::adapter.isInitialized) {
                adapter = TicketDetailAdapter(detail.operationItem)
                recyclerView.adapter = adapter
            }
            
            // 保存操作项列表到缓存
            // 将OperationItem列表转换为String列表以便存储
            val operationItemStrings = detail.operationItem.map { it.content ?: "" }
            Log.i(TAG, "缓存的数据: ${operationItemStrings}")
            AppDataManager.saveOperation("operation_items", operationItemStrings as java.io.Serializable)
            Log.i(TAG, "已保存操作项到缓存，数量: ${operationItemStrings.size}")
            
            // 根据status字段控制底部操作区域的显示/隐藏
            val bottomActionLayout = findViewById<LinearLayout>(R.id.llBottomAction)
            if (detail.status == "1") {
                Log.i(TAG, "状态为1，隐藏开始操作区域")
                bottomActionLayout.visibility = View.GONE
            } else {
                Log.i(TAG, "状态不为1，显示开始操作区域")
                bottomActionLayout.visibility = View.VISIBLE
            }
        } catch (e: Exception) {
            showError("数据显示异常: ${e.message}")
        }
    }

    private fun showError(message: String) {
        Log.e(TAG, "错误: $message")
    }

    // 定义请求码
    private val REQUEST_GLASS_CONNECTION = 1001
    
    /**
     * 初始化底部操作区域并添加点击事件
     */
    private fun initBottomButton() {
        try {
            val bottomAction = findViewById<TextView>(R.id.tvBottomAction)
            bottomAction.setOnClickListener { 
                Log.i(TAG, "底部按钮被点击，开始执行操作")

                // 检查设备连接状态
                if (!GlobalData.isGlassConnect()) {
                    Log.e(TAG, "设备未连接，跳转到连接页面")
                    Toast.makeText(this, "请先完成设备连接", Toast.LENGTH_LONG).show()

                    val intent = Intent(this@TicketDetailActivity, GlassConnectionActivity::class.java)
                    // 使用startActivityForResult等待连接结果
                    startActivityForResult(intent, REQUEST_GLASS_CONNECTION)
                } else {
                    Log.e(TAG, "设备已连接，执行操作")
                    // 设备已连接，直接执行后续操作
                    executeOperation()
                }
            }
        } catch (e: Exception) {
            Log.e(TAG, "底部按钮初始化失败", e)
        }
    }
    
    /**
     * 执行操作票操作的核心逻辑
     */
    private fun executeOperation() {
        try {
            // 首先发送WebSocket消息
            val oldTicketItem = intent.getSerializableExtra("ticket_item") as? OldTicketItem
            val operationTask = oldTicketItem?.operationTask ?: "未知任务"
            
            // 创建WebSocket消息
            val webSocketMessage = "{\"business\": 5, \"data\": \"$operationTask\"}"
            Log.i(TAG, "准备发送WebSocket消息: $webSocketMessage")
            
            // 注册临时的WebSocket处理器来处理响应
            val tempWebSocketHandler = object : SimpleWebSocketHandler {
                override fun onMessageReceived(type: WebSocketMessageType, message: String) {
                    Log.i("WebSocket-Detail", "收到消息: $message")
                    try {
                        // 解析JSON响应
                        val jsonObject = org.json.JSONObject(message)
                        val business = jsonObject.getInt("business")
                        val data = jsonObject.optString("data", "")
                        
                        // 检查是否是成功响应
                        if (business == 0 && data == "ok") {
                            Log.i(TAG, "收到确认消息，开始生成音频")
                            
                            // 生成长文本内容
                            val longText = "开始对${operationTask}操作票进行操作，开始识别铭牌"
                            
                            // 使用科大讯飞TTS生成语音
                            generateSpeech(longText, operationTask)
                            
                            // 注销临时处理器
                            WebSocketService.getInstance().unregisterHandler(this)
                        }
                    } catch (e: Exception) {
                        Log.e(TAG, "解析WebSocket响应失败: ${e.message}")
                    }
                }
                
                override fun onConnectionChanged(connected: Boolean) {
                    // 不需要特别处理连接状态变化
                }
                
                override fun onError(errorMsg: String) {
                    Log.e(TAG, "WebSocket错误: $errorMsg")
                }
            }
            
            // 注册临时处理器
            WebSocketService.getInstance().registerHandler(tempWebSocketHandler, this)

            sendWebSocketMessage(webSocketMessage, showToast = false)
        } catch (e: Exception) {
            Log.e(TAG, "执行操作异常: ${e.message}", e)
        }
    }

    /**
     * 检查眼镜设备连接状态，如果未连接则跳转到连接页面
     */
    private fun checkGlassConnection() {
        // 实际检查GlobalData中的连接状态
        if (!GlobalData.isGlassConnect()) {
            Log.e("TicketListActivity", "设备未连接，跳转到连接页面")
            Toast.makeText(this, "请先完成设备连接", Toast.LENGTH_LONG).show()

            val intent = Intent(this@TicketDetailActivity, GlassConnectionActivity::class.java)
            // 使用CLEAR_TOP标志，避免创建多个实例
            intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP
            startActivity(intent)
        } else {
            Log.e("TicketListActivity", "设备已连接，无需跳转")
        }
    }

    /**
     * 使用科大讯飞TTS生成语音
     * @param text 要转换为语音的文本
     */
    private fun generateSpeech(text: String, operationTask: String) {
        try {
            Log.i(TAG, "开始生成语音，文本长度: ${text.length}字符")
            
            // 使用XunfeiTtsUtil生成语音
            XunfeiTtsUtil.textToAudio(
                text = text,
                onAudioReady = { audioData ->
                    Log.i(TAG, "语音生成成功，音频数据长度: ${audioData.size}字节")
                    runOnUiThread {
                        // 发送操作任务
                        PSecuritySDK.getMessageService()?.sendTextMessageByP2P(operationTask)
                        // 发送音频数据
                        PSecuritySDK.getMessageService()?.sendAudioStreamDataByP2P(audioData)
                        Log.i(TAG, "已发送语音数据")

                        // 跳转到视频页面
                        val intent = Intent(this@TicketDetailActivity, VideoActivity::class.java)
                        intent.putExtra("ticket_id", tiketId)
                        intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP
                        startActivity(intent)
                    }
                },
                onError = { errorMsg ->
                    Log.e(TAG, "语音生成失败: $errorMsg")
                },
            )
        } catch (e: Exception) {
            Log.e(TAG, "语音生成过程中出现异常: ${e.message}", e)
        }
    }


    override fun onSupportNavigateUp(): Boolean {
        onBackPressed()
        return true
    }
    
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        
        if (requestCode == REQUEST_GLASS_CONNECTION) {
            // 从眼镜连接页面返回
            Log.i(TAG, "从GlassConnectionActivity返回，resultCode: $resultCode, GlobalData.isGlassConnect(): ${GlobalData.isGlassConnect()}")
            
            // 根据用户需求修改：连接成功后不自动执行操作，让用户再次点击按钮
            if (resultCode == RESULT_OK) {
                // 连接成功，显示提示让用户再次点击按钮
                Log.i(TAG, "眼镜连接成功，请再次点击'开始操作'按钮")
                Toast.makeText(this, "设备连接成功，请再次点击'开始操作'按钮", Toast.LENGTH_LONG).show()
            } else {
                // 连接失败或取消
                Log.i(TAG, "眼镜连接失败或取消连接")
            }
        }
    }

    override fun onResume() {
        super.onResume()
        // 当从VideoActivity返回时，重新加载票据详情数据
        if (tiketId != null) {
            Log.i("TicketDetailActivity", "从VideoActivity返回，重新加载票据详情，ID: $tiketId")
            viewModel.loadTicketDetail(tiketId!!)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
    }
}
